package cn.com.ddapp.ddm.fragment.base;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhy.autolayout.AutoRelativeLayout;
import java.net.URLDecoder;
import butterknife.BindView;
import butterknife.OnClick;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.mine.CircleView;
import cn.com.ddapp.ddm.bean.mine.MyCall;
import cn.com.ddapp.ddm.bean.mine.NotReadMsg;
import cn.com.ddapp.ddm.bean.mine.UserData;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.AboutActivity;
import cn.com.ddapp.ddm.ui.CircleManageActivity;
import cn.com.ddapp.ddm.ui.CollectionActivity;
import cn.com.ddapp.ddm.ui.LoginActivity;
import cn.com.ddapp.ddm.ui.NearStoreDetailsActivity;
import cn.com.ddapp.ddm.ui.OpinionActivity;
import cn.com.ddapp.ddm.ui.ShareActivity;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.ui.mine.CouponsActivity;
import cn.com.ddapp.ddm.ui.mine.InfoCenterActivity;
import cn.com.ddapp.ddm.ui.mine.MyMoneyActivity;
import cn.com.ddapp.ddm.ui.mine.PersonCenterActivity;
import cn.com.ddapp.ddm.ui.mine.SettingActivity;
import cn.com.ddapp.ddm.ui.order.OrderListActiviy;
import cn.com.ddapp.ddm.util.NetUtils;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.widget.CircleImageView;
import cn.com.ddapp.ddm.widget.TipsToast;

/**
 * Created by Administrator on 2016/8/16 0016.
 */
public class MineFragment extends BaseFragment {

    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.error_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.headimg)
    CircleImageView headImg;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.msg_account)
    CircleView msgAccount;
    @BindView(R.id.msg_account1)
    TextView msgAccount1;
    //TextView msgAccount;

    String nickName, sheadImg, birthDay, userId, myPhone;
    int sex;
    double wallet;
    UserData userData;
    int msgAcc ;
    OkUtilCallback callback, callback1;
    int TOPERSONCENTER = 201;
    int TOMYMONEY = 202;
    //横竖屏
    int orientation;
    @BindView(R.id.recommend)
    TextView recommend;
    @BindView(R.id.call)
    AutoRelativeLayout call;
    Bitmap bitmap = null;
    @BindView(R.id.login)
    TextView login;

    private LogoutReciver logoutReciver = new LogoutReciver();
    private AgainReciver againReciver = new AgainReciver();

    @Override
    protected String getFragmentTag() {
        return null;
    }

    @Override
    protected void initData() {
        userId = SPUtils.getStringData(getActivity(), SPUtils.USERID);
        Log.e("111","userId="+userId);
        if (!NetUtils.isConnected(getActivity())) {
            Toast.makeText(getActivity(), "请检查你的网络", Toast.LENGTH_SHORT).show();
        } else {
            //mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            callback = new OkUtilCallback() {
                @Override
                public void onMyResponse(String response, int id) {
                    Gson gson = new Gson();
                    userData = gson.fromJson(response, UserData.class);
                    if ((!AppConfig.RESULT_OK.equalsIgnoreCase(userData.getResult()))) {
                        BaseApplication.getIntstance().showToast(userData.getResult(), Toast.LENGTH_SHORT, 0, Gravity.CENTER);
                    } else {
                        if (userData.getUser() != null) {
                            birthDay = userData.getUser().getBirthday();
                            sex = userData.getUser().getSex();
                            nickName = userData.getUser().getName();
                            sheadImg = userData.getUser().getHeadImg();
                            wallet = userData.getUser().getWallet();
                            SPUtils.setStringData(getActivity(), SPUtils.USERPATH, sheadImg);
                            SPUtils.setStringData(getActivity(), SPUtils.USERNAME, nickName);
//                            SPUtils.setStringData(getActivity(),SPUtils.BIRTHDAY,birthDay);
                            SPUtils.setIntData(getActivity(), SPUtils.USERSEX, sex);
                            if (!TextUtils.isEmpty(sheadImg)) {
                                if(sheadImg.contains("http")){
                                    Glide.with(getActivity()).load(sheadImg).into(headImg);
                                }else{
                                    Glide.with(getActivity()).load(OKUtilAPI.imgBaseUrl + sheadImg).into(headImg);
                                }
                            }

                            /*if (!TextUtils.isEmpty(sheadImg)) {
                                Bitmap bit = getBitmap(OKUtilAPI.imgBaseUrl + sheadImg);
                                bitmap = zoomImg(bit, 260, 260);
                                headImg.setImageBitmap(bitmap);
                            }*/
                            /*Glide.with(getActivity()).load(OKUtilAPI.imgBaseUrl + sheadImg)
                                    .placeholder(R.mipmap.src)
                                    .into(headImg);*/
                            try {
                                name.setText(URLDecoder.decode(nickName, "utf-8"));
                                money.setText(NetUtils.setDecimal(wallet) + "");
                            }catch (Exception e){
                                e.printStackTrace();
                            }


                        }
                    }
                }
            };

            //请求会员资料
            OKUtilAPI.post(OKUtilAPI.getUser, "userId=" + userId, callback);

            callback1 = new OkUtilCallback() {
                @Override
                public void onMyResponse(String response, int id) {
                    Gson gson = new Gson();
                    MyCall call = gson.fromJson(response, MyCall.class);
                    if ((!AppConfig.RESULT_OK.equalsIgnoreCase(call.getResult()))) {
                        //mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
                    } else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(call.getResult()))) {
                        BaseApplication.getIntstance().showToast(call.getResult(), Toast.LENGTH_SHORT, 0, Gravity.CENTER);
                    } else {
                        if (call.getContent() != null) {
                            myPhone = call.getContent();
//                            phone.setText(myPhone);
                        }
                    }
                }
            };
            //客服热线
            OKUtilAPI.post(OKUtilAPI.art, "type=4", callback1);

            final OkUtilCallback okUtilCallback = new OkUtilCallback() {
                @Override
                public void onMyResponse(String response, int id) {
                    NotReadMsg bean = gson.fromJson(response, NotReadMsg.class);
                    if (!bean.getResult().equals("OK")) {
                        //mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
//                        BaseApplication.showToast(bean.getResult());
                    } else {
                        msgAcc = bean.getCount();
                        if (msgAcc == 0) {
                            msgAccount.setVisibility(View.GONE);
                            msgAccount1.setVisibility(View.GONE);
                        } else {
                            //1竖屏0横屏
                            if (orientation == 1) {
                                msgAccount.setVisibility(View.GONE);
                                msgAccount1.setVisibility(View.VISIBLE);
                                msgAccount1.setText(msgAcc + "");
                            }
                            if (orientation == 2 || orientation == 0) {
                                msgAccount.setVisibility(View.VISIBLE);
                                msgAccount1.setVisibility(View.GONE);
                                msgAccount.setBackgroundColor(Color.RED);
                                msgAccount.setNotifiText(msgAcc);
                            }
                        }
                    }
                }
            };
            OKUtilAPI.post(OKUtilAPI.notReadMsg, "userId=" + userId, okUtilCallback);
        }
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        //判断是否横屏,1竖屏0横屏
        orientation = getActivity().getResources().getConfiguration().orientation;
        if (orientation == 1) {
            recommend.setVisibility(View.VISIBLE);
            call.setVisibility(View.VISIBLE);
            //未登录
            if (!SPUtils.getBooleanData(getActivity(), SPUtils.ISLOGIN)) {
                login.setVisibility(View.VISIBLE);
                name.setVisibility(View.GONE);
            } else {
                login.setVisibility(View.GONE);
                name.setVisibility(View.VISIBLE);
            }
        }
        phone.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
        initBroast();
    }

    private void initBroast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("logout");
        getActivity().registerReceiver(logoutReciver, filter);

        IntentFilter filter1 = new IntentFilter();
        filter1.addAction("again");
        getActivity().registerReceiver(againReciver, filter1);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.me_fragment;
    }

    Dialog callDialog;
    @OnClick({R.id.about_us, R.id.help, R.id.call, R.id.login})
    void onClick(View view) {
        Intent intent;
        if (!NetUtils.isConnected(getActivity())) {
            Toast.makeText(getActivity(), "请检查你的网络", Toast.LENGTH_SHORT).show();
        } else {
            switch (view.getId()) {
                case R.id.call:
                    if (!"".equals(myPhone)) {
                        callDialog=new Dialog(getActivity());
                        callDialog.setContentView(R.layout.nearshop_dialog);
                        TextView custom_tell= (TextView) callDialog.findViewById(R.id.custom_tell);
                        TextView details_map= (TextView) callDialog.findViewById(R.id.details_map);
                        TextView details_dismiss= (TextView) callDialog.findViewById(R.id.details_dismiss);
                        custom_tell.setText(myPhone);
                        details_map.setVisibility(View.GONE);
                        custom_tell.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                               Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + myPhone));//跳转到拨号界面，同时传递电话号码
                                startActivity(intent);
                                callDialog.dismiss();
                            }
                        });
                        details_dismiss.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                callDialog.dismiss();
                            }
                        });
                        Window window=callDialog.getWindow();
                        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                        callDialog.setCanceledOnTouchOutside(true);
                        WindowManager.LayoutParams params=callDialog.getWindow().getAttributes();
                        params.gravity=Gravity.BOTTOM;
                        callDialog.getWindow().setAttributes(params);
                        try{
                            Context context = callDialog.getContext();
                            int divierId = context.getResources().getIdentifier("android:id/titleDivider", null, null);
                            View divider = callDialog.findViewById(divierId);
                            divider.setBackgroundColor(Color.TRANSPARENT);
                        }catch(Exception e){
                            //去除Holo主题的蓝色线条
                            e.printStackTrace();
                        }
                        callDialog.show();

                    }
                    break;
                case R.id.about_us:
                    intent = new Intent(getActivity(), AboutActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("category", "1");
                    intent.putExtra("ABOUT", bundle);
                    startActivity(intent);
                    break;
                case R.id.login:
                    intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    break;
                case R.id.help:
                    intent = new Intent(getActivity(), AboutActivity.class);
                    Bundle bundl2e = new Bundle();
                    bundl2e.putString("category", "2");
                    intent.putExtra("ABOUT", bundl2e);
                    startActivity(intent);
                    break;
            }
        }
    }

    @OnClick({R.id.coupon, R.id.personage, R.id.settingL, R.id.recommend, R.id.feedback, R.id.collect, R.id.orderList, R.id.moneyL, R.id.share, R.id.message_me})
    void onclick(View v) {
        Intent intent;
        if (!NetUtils.isConnected(getActivity())) {
            Toast.makeText(getActivity(), "请检查你的网络", Toast.LENGTH_SHORT).show();
        } else {
            if (SPUtils.getBooleanData(getActivity(), SPUtils.ISLOGIN)) {
                switch (v.getId()) {
                    case R.id.coupon:
                        intent = new Intent(getActivity(), CouponsActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.orderList:
                        intent = new Intent(getActivity(), OrderListActiviy.class);
                        startActivity(intent);
                        break;
                    case R.id.message_me:
                        intent = new Intent(getActivity(), InfoCenterActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.personage:
                        intent = new Intent(getActivity(), PersonCenterActivity.class);
                        intent.putExtra("nickName", nickName);
                        intent.putExtra("sheadImg", sheadImg);
                        intent.putExtra("bitmap", bitmap);
                        intent.putExtra("birthDay", birthDay);
                        intent.putExtra("sex", sex);
                        startActivityForResult(intent, TOPERSONCENTER);
                        break;
                    case R.id.settingL:
                        intent = new Intent(getActivity(), SettingActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.share:
                        intent = new Intent(getActivity(), CircleManageActivity.class);
                        intent.putExtra("nickName", nickName);
                        intent.putExtra("sheadImg", sheadImg);
                        intent.putExtra("bitmap", bitmap);
                        startActivity(intent);
                        break;
                    case R.id.collect:
                        intent = new Intent(getActivity(), CollectionActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.feedback:
                        intent = new Intent(getActivity(), OpinionActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.recommend:
                        intent = new Intent(getActivity(), ShareActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.moneyL:
                        intent = new Intent(getActivity(), MyMoneyActivity.class);
                        intent.putExtra("wallet", wallet + "");
                        intent.putExtra("sheadImg", sheadImg);
                        Log.e("111mine",sheadImg);
                        intent.putExtra("bitmap", bitmap);
                        startActivityForResult(intent, TOMYMONEY);
                        break;
                }
            } else {
                BaseApplication.getIntstance().showToast("请登录", Toast.LENGTH_SHORT, 0, Gravity.CENTER);
                intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        TipsToast.makeText(getActivity(), "onActivityResult", TipsToast.LENGTH_LONG);
        if (requestCode == TOPERSONCENTER) {
            if (resultCode == 2) {
                Bundle bundle = data.getExtras();
                name.setText(bundle.getString("userName"));
                bitmap = bundle.getParcelable("photo");
                if (bitmap != null) {
                    headImg.setImageBitmap(bitmap);
                }
            }
        }
        if (requestCode == TOMYMONEY) {
            if (resultCode == 8) {
                String m = data.getStringExtra("money");
                money.setText(NetUtils.setDecimal(Double.parseDouble(m)) + "");
            }
        }
    }


    public class LogoutReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("logout")) {
                if (SPUtils.getBooleanData(getActivity(), SPUtils.ISLOGIN)){
                    initData();
                }else{
                    Log.i("aaa","oooo1");
                    msgAccount.setVisibility(View.GONE);
                    msgAccount1.setVisibility(View.GONE);
                    msgAccount1.setText("");
                    headImg.setImageResource(R.mipmap.src);
                    login.setVisibility(View.VISIBLE);
                    name.setVisibility(View.GONE);
                    money.setText("");
                }
            }
        }
    }

    public class AgainReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("again")) {
                initData();
            }
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        initData();
        initBroast();
        Log.i("huaG","onResume");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(logoutReciver);
        getActivity().unregisterReceiver(againReciver);
    }

    //在此界面登录之后会执行
    @Override
    public void onStart() {
        super.onStart();
        initData();
        orientation = getActivity().getResources().getConfiguration().orientation;
        if (orientation == 1) {
            recommend.setVisibility(View.VISIBLE);
            call.setVisibility(View.VISIBLE);
            //未登录
            if (!SPUtils.getBooleanData(getActivity(), SPUtils.ISLOGIN)) {
                login.setVisibility(View.VISIBLE);
                name.setVisibility(View.GONE);
                msgAccount.setVisibility(View.GONE);
                headImg.setImageResource(R.mipmap.src);
            } else {
                login.setVisibility(View.GONE);
                name.setVisibility(View.VISIBLE);
            }
        }else{
            if (!SPUtils.getBooleanData(getActivity(), SPUtils.ISLOGIN)) {
                login.setVisibility(View.VISIBLE);
                name.setVisibility(View.GONE);
            } else {
                login.setVisibility(View.GONE);
                name.setVisibility(View.VISIBLE);
            }
        }
    }
}
